#!/usr/local/bin/perl

use Net::POP3;

if(@ARGV<5) {
	print "usage: adminpop.pl server user pass dir del\n";
	exit;
}
$server = $ARGV[0];
$username = $ARGV[1];
$password = $ARGV[2];
$dir = $ARGV[3];
$del = $ARGV[4];

use Sys::Hostname;
$host = hostname;

#print "$server:$username:$password:$dir:$del\n";

# Constructors
$pop = Net::POP3->new($server, Timeout => 60);
$ret = $pop->login($username, $password);
if ($ret > 0) {
	my $msgnums = $pop->list; # hashref of msgnum => size
	print "$username, total ".(keys %$msgnums)." msgs\n";
	foreach my $msgnum (sort {$a<=>$b} keys %$msgnums) {
		my $msg = $pop->get($msgnum);
		if($msg) {
			$fn = "$dir/Maildir/new/".time.'.'.$$.".$msgnum.".$msgnums->{$msgnum}.".$host";
			if(open FH, ">$fn") {
				print FH @$msg;
				close FH;
				print $msgnum,",$fn";
				chown 80,80,$fn;
				if($del) {
					$pop->delete($msgnum);
					print ",del";
				}
				print "\n";
			}
		}
	}
} elsif($ret) {
	print "0 msg\n";
} else {
	print "err login\n";
}

$pop->quit;

